package com.xm.xmapp.customview;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;

import com.xm.xmapp.R;

public class LoadingDialog extends Dialog {

	private LayoutInflater inflater;
	private View view;
	private LayoutParams lp;
	private boolean isDismiss = true;// 默认返回键以及外部点击可以关闭dialog
	private TextView tv_msg;

	private MyProgressBar myprogressbar;

	public LoadingDialog(Context context) {
		super(context, R.style.Dialog);
		inflater = LayoutInflater.from(context);
		view = inflater.inflate(R.layout.dialog_loading, null);
		tv_msg = (TextView) view.findViewById(R.id.loading_tv_msg);
		myprogressbar = (MyProgressBar) view.findViewById(R.id.myprogressbar);

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(view);
		setOutIsClick();
		this.setCanceledOnTouchOutside(false);
	}

	public LoadingDialog setOutIsClick() {
		try {
			// 设置点击对话框之外不能消失
			setCanceledOnTouchOutside(isDismiss);
			// 设置window属性
			lp = getWindow().getAttributes();
			lp.gravity = Gravity.CENTER;
			lp.dimAmount = 0; // 去背景遮盖
			lp.alpha = 1.0f;
			getWindow().setAttributes(lp);
		} catch (Exception e) {
			//
		}
		return this;
	}

	public void setLoadingText(String text) {
		if (!TextUtils.isEmpty(text)) {
			tv_msg.setText(text);
		} else {
		}
	}

	/**
	 * 设置当用户点击手机返回按钮时，是否关闭dialog，true是，false不关闭
	 * 
	 * @param isDismiss
	 */
	public LoadingDialog setBackKeyDownIsDismiss(boolean isDismiss) {
		this.isDismiss = isDismiss;
		setOutIsClick();
		return this;
	}

	/**
	 * 重写返回按钮，实现两次退出功能
	 */
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int codekey = event.getKeyCode();
		if (codekey == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN && !isDismiss) {
			return true;// 必须返回true
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	public void dismiss() {

		if (this.isShowing()) {
			super.dismiss();
		}
		myprogressbar.cancel();
	}

	@Override
	public void show() {

		if (!this.isShowing()) {

			super.show();
			myprogressbar.show();
		}
	}

}
